<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import dayjs from 'dayjs';
import {
  getCurrentInstance,
  showToast,
  hideLoading,
  showLoading,
  usePullDownRefresh,
  stopPullDownRefresh,
  useShareAppMessage,
  requestPayment,
  showModal
} from '@tarojs/taro';
import { processRichText } from '@/composables';
import { useRouterPush } from '@/composables';
import { useNurseGoods } from '@/service';
import { useNurseOrders } from '@/service';
import { useImage } from '@/hooks';
import { storeToRefs } from 'pinia';
import { useAuthStore, useGoodsStore, useTempShopStore } from '@/store';
const { toOrders } = useRouterPush();
import part1 from './part1.vue';
import part2 from './part2.vue';
import part3 from './part3.vue';
// import part4 from './part4.vue';
import part5 from './part5.vue';
import know from './know.vue';
import partGoods from './part-goods.vue';
import care from '@/components/basic-comm/care.vue';
import pic from '@/assets/ico/info.jpg';
import LoginStatusCheck from '@/components/login-status-check/index.vue';
import { AppName } from '@/constants';
import { PlatformUtils } from '@/utils';
const part1Ref = ref();
const part2Ref = ref();
const part3Ref = ref();
const partGoodsRef = ref();
const loginStatusRef = ref();
const { nurseUser, curFamily } = storeToRefs(useAuthStore());

const { getGoodsDetail } = useNurseGoods();
const { toHelp, toGoodsPay, toMine, toHealthCode } = useRouterPush();
const { addByWeChat, payByWeChat, queryByWeChat, closeByWeChat, getFeeControl } = useNurseOrders();
const goodsStore= useGoodsStore();
const tempShopStore = useTempShopStore();


import { precisionAdd } from '@/utils/precision';

// 计算总合计（包含商品费用和临时商店费用）
const grandTotal = computed(() => {
  return precisionAdd(goodsStore.totalFee, tempShopStore.getTotalPrice);
});

const {
  router: {
    params: { id, pname, unit, nurseType, goods_type, nurseTypeText, duration }
  }
}: any = getCurrentInstance();

const {
  router: { $taroPath }
}: any = getCurrentInstance();

const isHuaSheng = computed(() => {
  // return nurseUser.value?.defaultHospitalName?.includes('华声');
  // return AppName == 'huasheng'
  return PlatformUtils.isHuaSheng();
});


useShareAppMessage(res => {
  return {
    title: pname,
    path: $taroPath, // 路由路径
    imageUrl: data.value?.goods?.imagePath
  };
});

definePageConfig({
  navigationBarTitleText: pname,
  enablePullDownRefresh: true,
  enableShareAppMessage: true
});

// Taro.setNavigationBarTitle({
//     title: type == 1 ? '申请开票' : '发票详情'
// })

getData();

usePullDownRefresh(() => {
  getData();
  stopPullDownRefresh();
});

const data = ref();

const list = ref([]);

const index = ref();

function getItem(index: number) {
  const item: any = list.value[index];
  let images = item?.pic?.split(',');
  images = images.map((el: string) => {
    return useImage(el);
  });
  let descriptionPic = item?.descriptionPic?.split(',');
  descriptionPic = (descriptionPic || []).map((el: string) => {
    return useImage(el);
  });
  const skuList = list.value.map((el: any, i) => {
    return { index: i, name: el.goodsName, id: el.id, active: i == index, disable: false };
  });
  return {
    id: item.id,
    images,
    price: item.price,
    descriptionPic,
    unit,
    duration,
    sku: [
      {
        name: '类型规格',
        list: [...skuList]
      }
    ],
    goods: {
      skuId: item.id,
      price: item.price,
      name: item.goodsName,
      imagePath: useImage(item.tpic)
    }
  };
}

async function getData() {
  showLoading({ title: '正在请求数据...' });

  const { error, success } = await getGoodsDetail({ goods_id: id, goods_type });

  if (!error && success?.length > 0) {
    list.value = success;
    goodsStore.init(success?.[0]?.standardCode || 1);
    goodsStore.duration = list.value?.[0]?.duration || 60;
    goodsStore.price = list.value?.[0]?.price || 0;
    index.value = 0;
    data.value = getItem(index.value);
  }
  hideLoading();
}

const visible = ref(false);

const selectSku = (ss: { sku: any }) => {
  const { sku } = ss;
  data.value = getItem(sku.index);
};

const val = ref(1);

const num = ref(1);

const onChange = (index: number) => {
  val.value = index + 1;
};

function toPay() {
  if (!nurseUser.value.phone) {
    showToast({
      title: '请先完善用户信息！',
      icon: 'none',
      duration: 1500
    });
    setTimeout(() => {
      toMine(1);
    }, 1500);
    return;
  }
  toGoodsPay({
    goodsId: data.value?.goods.skuId,
    pid: id,
    pname,
    nurseType,
    name: data.value?.goods.name,
    num: num.value,
    pic: data.value?.goods.imagePath,
    price: data.value?.goods.price,
    unit,
    nurseTypeText
  });
}

const agree = ref(false);
const payLoading = ref(false); // 支付加载状态，防止重复点击
const showFeeDetail = ref(false); // 费用明细展开/折叠状态
// let timers = 0
// const totalPrice = ref(0)
onMounted(() => {
  // timers = setInterval(() => {
  //   totalPrice.value = (part1Ref.value.getPrice() + part2Ref.value.getPrice()) * part3Ref.value.getTimes();
  //   preCharge.value = totalPrice.value;
  // }, 1600)
});
onBeforeUnmount(() => {
  // clearInterval(timers)

})

function getAddrId() {
  const ary = nurseUser.value?.nurseHomeAddrList || []
  if(ary.length){
    let id = ary[0].id
    ary.forEach(i=>{
      if(i.isDefault == 1){
        id = i.id
      }
    })
    return id;
  }
  return '';
}

async function actionPay(){
  const addrId = getAddrId();
  if(!addrId){
    showToast({
      title: '请添加居家地址',
      icon: 'none'
    });
    return
  }
  // 防止重复点击
  if (payLoading.value) {
    return;
  }
  
  payLoading.value = true;
  
  try {
    // 检查登录状态
    if (!loginStatusRef.value?.requireLogin?.({
      title: '提示',
      content: '请先登录才能购买商品'
    })) {
      return;
    }

    // 健康码校验：未注册则提示并引导去注册
    if (!useAuthStore().isRegistered) {
      showModal({
        title: '提示',
        content: isHuaSheng.value ? '您未注册健康码，请先注册再购买。' :  '您未注册诊疗卡，请先注册再购买。',
        confirmText: '去注册',
        cancelText: '取消'
      }).then((res) => {
        if (res.confirm) {
          toHealthCode();
        }
      });
      return;
    }

    // console.log("goodsStore", goodsStore)

    if(!goodsStore.beginDate || !goodsStore.endDate){
      showToast({
        title: '请选择期望上门时间',
        icon: 'none',
        duration: 2000
      })
      return
    }

    //如果goodsStore.beginDate 和现在距离不足3小时，则提示不能下单
    const beginDate = dayjs(goodsStore.beginDate);
    const now = dayjs();
    const diffHours = beginDate.diff(now, 'hour', true); // 精确到小时，保留小数
    if(diffHours < 3){
      showToast({
        title: '请选择3小时后的时间',
        icon: 'none',
        duration: 2000
      })
      return
    }

  const goodsName = data.value?.goods.name
  // const {beginDate, endDate} = part2Ref.value.getTimestr()
  const param: any = {
    // name: "画画15677889900",
    address: "广西壮族自治区南宁市青秀区玩儿",
    hospital: nurseUser.value.defaultHospitalName || "广西医科大学第二附属医院护理科护理001",
    hospitalId: nurseUser.value.defaultHospital || "1",
    nurseUserOrdersDetails: [
      {
        // price: data.value?.goods.price,//"0.01",
        price: goodsStore.sku.cur?.price || 0,
        unit: "小时",
        num: goodsStore.times,
        goodsName: goodsName,// "生命体征测量",
        // goodsId: data.value?.goods.skuId, //"1914524002470748161",
        pname: pname, //"生命体征测量",
        pid: id, //"1914523872334077953",
        goodsId: id,

      }
    ],
    specialDetails: [],
    specialAmt: "",
    // beginDate: "2025-06-17 00:00:00",
    // endDate: "2025-06-17 23:59:59",
    remark: goodsStore.remark,
    addrId: addrId, // "1926457126490406914",
    familyId: curFamily.value?.id || -1, //"1926457126146473985",
    userId: nurseUser.value.id, //"1923575925480013825"
    orderText: data.value?.goods.name || "[生命体征测量]-[生命体征测量]",
    nurseType: nurseType, // "2",
    // end: 0,
    nightId: goodsStore.night.choose ? goodsStore.night.options[0]?.id : -1,//夜间费ID
    isGoHome: goodsStore.pickup.choose ? "1" : "0",
    ispickup: goodsStore.pickup.choose ? "1" : "0",
    urgentId: goodsStore.urgent.cur?.id || -1,//加急ID
    urgentName: goodsStore.urgent.cur?.name || "不指定",
    urgentFee: goodsStore.urgentFree,
    expertId: goodsStore.expert.cur?.id || -1,//专家ID
    expertName: goodsStore.expert.cur?.name || "不指定",
    expertFee: goodsStore.expertTotalFee,
    distanceId: goodsStore.distance.id,//远程费ID
    distanceName: "远程费",
    distanceFee: goodsStore.distanceTotalFee,
    distanceOldFee: goodsStore.distanceFee,
    expertOldFee: goodsStore.expertFree,
    totalPrice: grandTotal.value,

    expertNum: 1,
    distanceNum: 1,
    standardId: goodsStore.sku.cur?.id || '',//规格ID
  }

  if(tempShopStore.hasGoods){
    const medicationOrderDetailS: any[] = []
    tempShopStore.goodsList.forEach(item => {
      medicationOrderDetailS.push({
        goodsId: item.id,
        num: parseInt(tempShopStore.numMap[item.id]),
        goodsName: item.typeName,
      })
    })
    param.medicationOrderDetails = medicationOrderDetailS
  }
  const all = {
    ...param,
      beginDate: goodsStore.beginDate,
      endDate: goodsStore.endDate,
      // beginDate: `${formData.value.beginDate} 00:00:00`,
      // endDate: `${formData.value.endDate} 23:59:59`,
      orderText: `[${nurseTypeText}]${pname !== goodsName ? `[${pname}]` : ''}-[${goodsName}]`
  }
   const { error, success } = await addByWeChat({
      ...all,
      orderJson: JSON.stringify(all)
  });

  if (!error && success) {
      showToast({
          title: '下单成功',
          icon: 'success',
          duration: 2000
      });
      // payInfo = success;
      const { timestamp, noncestr, package: packAge, sign } = success;

      await requestPayment({
        timeStamp: timestamp,
        nonceStr: noncestr,
        package: packAge,
        paySign: sign,
        signType: 'RSA',
        fail: () => {
            // if (pay !== '1') toOrders();
            showToast({
                title: '支付失败',
                icon: 'none',
                duration: 2000
            })
        },
        complete() {
            hideLoading();
            // loading.value = false;
        },
        success: res => {
            if (res.errMsg == 'requestPayment:ok') {
                showToast({
                    title: '支付成功！',
                    icon: 'success',
                    duration: 1500
                });
                setTimeout(() => {
                    toOrders();
                }, 1500);
            }
        }
    });
  }
  else{
    showToast({
      title: error?.message || "下单失败",
      icon: 'none',
      duration: 2000
    })
  }
  } catch (err) {
    showToast({
      title: '操作失败，请重试',
      icon: 'none',
      duration: 2000
    });
  } finally {
    payLoading.value = false;
  }
}

const preCharge = ref(0)

</script>
<template>
  <basic-layout>
    <!-- <custom-navbar :title="pname" showLeft /> -->
    <!-- 登录状态检查组件 -->
    <LoginStatusCheck ref="loginStatusRef" />

    <view class="w-375px text-primary flex-col-center">
      <view class="w-360px flex-col-center m-b-15">
        <view class="bg-#fff mt-2 b-rounded-3 shadow w-full">
          <nut-swiper :auto-play="0" :loop="false" class="b-rounded-t-3" :init-page="val" @change="onChange">
            <nut-swiper-item v-for="(item, index) in data?.images" :key="index" class="swiper_item">
              <image :src="item" alt="" class="swiper_img" draggable="false" mode="aspectFill" />
            </nut-swiper-item>
            <template #page>
              <view class="swiper-pagination">{{ val }}/{{ data?.images?.length }}</view>
            </template>
          </nut-swiper>

          <view class="m-2 flex my-2 justify-between items-start">
            <view class="flex-1 text-24rpx">{{ pname }}</view>
            <view class="font-bold text-24rpx text-#e11d48">技术服务费: ¥{{ goodsStore.price || 0 }}</view>
          </view>
        </view>


        <part1 v-if="data" :obj="data" ref="part1Ref" />
        <part2 ref="part2Ref" />
        <part3 ref="part3Ref" :preCharge="preCharge" />

        <image class="w-full my-2" :src="pic" mode="widthFix" />
        <!-- <view v-html="list[0]?.description"></view> -->
        <rich-text :nodes="processRichText(list[0]?.description)" />

        <view class="bg-#fff my-2 b-rounded-3 shadow w-full flex-col-center">
          <view class="w-350px flex-col-center m-b-2">
            <view class="font-bold ml-2 m-t-2 text-lg">服务详情</view>
            <rich-text :nodes="processRichText(list[0]?.descriptionPic)" class="w-full rchs" />
            <!-- <image v-for="item in data?.descriptionPic" class="swiper_img m-t-2" mode="widthFix" draggable="false"
              alt="" :src="item" /> -->
          </view>
        </view>

        <partGoods ref="partGoodsRef" :preCharge="preCharge" />


        <!-- <part5 v-model="agree" /> -->
        <!-- <part4 :desc="list[0]?.description" /> -->
        <!-- <care /> -->
        <know v-model="agree" />

      </view>
      <view class="w-375px bg-white pos-fixed pos-bottom-0px pos-left-0 flex-col-center z-3">
        <!-- 合计和费用明细 -->
        <view class="box-border w-full bg-[#f0f0f0]">
          <view class="px-[32rpx] py-[24rpx] flex items-center justify-between cursor-pointer" @tap="showFeeDetail = !showFeeDetail">
            <text class="text-[28rpx] font-medium">合计：</text>
            <view class="flex items-center gap-[16rpx]">
              <text class="text-[32rpx] text-red-500 font-bold">¥{{ grandTotal }}</text>
              <view class="transition-transform" :class="showFeeDetail ? 'rotate-180' : ''">
                <text class="text-[24rpx] text-gray-500">▼</text>
              </view>
            </view>
          </view>
          
          <!-- 费用明细（可折叠） -->
          <view v-if="showFeeDetail" class="px-[32rpx] pb-[24rpx] border-t border-gray-200">
            <view class="pt-[20rpx] space-y-[16rpx]">
              <!-- 项目规格配置 -->
              <view v-if="(goodsStore.sku.cur as any)?.name" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">项目规格：</text>
                <text class="text-[24rpx] text-gray-800">{{ (goodsStore.sku.cur as any).name }}</text>
              </view>
              
              <!-- 基础费用（规格价格 + 技术服务费） -->
              <view class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">基础费用：</text>
                <text class="text-[24rpx] text-gray-800">
                  ¥{{ precisionAdd((goodsStore.sku.cur as any)?.price || 0, goodsStore.price || 0) }}
                  <text v-if="goodsStore.times > 1" class="text-[20rpx] text-gray-500"> × {{ goodsStore.times }}</text>
                </text>
              </view>
              
              <!-- 规格价格明细 -->
              <view v-if="(goodsStore.sku.cur as any)?.price" class="flex items-center justify-between pl-[24rpx]">
                <text class="text-[22rpx] text-gray-500">规格价格：</text>
                <text class="text-[22rpx] text-gray-600">¥{{ (goodsStore.sku.cur as any).price }}</text>
              </view>
              
              <!-- 技术服务费明细 -->
              <view v-if="goodsStore.price" class="flex items-center justify-between pl-[24rpx]">
                <text class="text-[22rpx] text-gray-500">技术服务费：</text>
                <text class="text-[22rpx] text-gray-600">¥{{ goodsStore.price }}</text>
              </view>
              
              <!-- 数量（仅在大于1时显示） -->
              <view v-if="goodsStore.times > 1" class="flex items-center justify-between pl-[24rpx]">
                <text class="text-[22rpx] text-gray-500">数量：</text>
                <text class="text-[22rpx] text-gray-600">{{ goodsStore.times }}次</text>
              </view>
              
              <!-- 远程费 -->
              <view v-if="goodsStore.distanceFee" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">远程费：</text>
                <text class="text-[24rpx] text-gray-800">¥{{ goodsStore.distanceFee }}</text>
              </view>
              
              <!-- 技术服务费（如果单独显示） -->
              <view v-if="goodsStore.distanceTotalFee && goodsStore.distanceTotalFee !== goodsStore.distanceFee" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">远程费（含超时）：</text>
                <text class="text-[24rpx] text-gray-800">¥{{ goodsStore.distanceTotalFee }}</text>
              </view>
              
              <!-- 加急费 -->
              <view v-if="goodsStore.urgentFree" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">加急费：</text>
                <text class="text-[24rpx] text-gray-800">¥{{ goodsStore.urgentFree }}</text>
              </view>
              
              <!-- 夜班费 -->
              <view v-if="goodsStore.nightFree" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">夜班费：</text>
                <text class="text-[24rpx] text-gray-800">¥{{ goodsStore.nightFree }}</text>
              </view>
              
              <!-- 专家费 -->
              <view v-if="goodsStore.expertFree" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">专家费：</text>
                <text class="text-[24rpx] text-gray-800">¥{{ goodsStore.expertFree }}</text>
              </view>
              
              <!-- 节假日费 -->
              <view v-if="goodsStore.festivalFree" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">节假日费：</text>
                <text class="text-[24rpx] text-gray-800">¥{{ goodsStore.festivalFree }}</text>
              </view>
              
              <!-- 接送费 -->
              <view v-if="goodsStore.pickupFree" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">接送费：</text>
                <text class="text-[24rpx] text-gray-800">¥{{ goodsStore.pickupFree }}</text>
              </view>
              
              <!-- 超时费 -->
              <view v-if="goodsStore.overtimeFee" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">超时费：</text>
                <text class="text-[24rpx] text-gray-800">¥{{ goodsStore.overtimeFee }}</text>
              </view>
              
              <!-- 临时商店费用 -->
              <view v-if="tempShopStore.getTotalPrice" class="flex items-center justify-between">
                <text class="text-[24rpx] text-gray-600">其他费用：</text>
                <text class="text-[24rpx] text-gray-800">¥{{ tempShopStore.getTotalPrice }}</text>
              </view>
              
              <!-- 分隔线 -->
              <view class="border-t border-gray-300 my-[12rpx]"></view>
              
              <!-- 小计 -->
              <view class="flex items-center justify-between">
                <text class="text-[26rpx] font-medium text-gray-700">小计：</text>
                <text class="text-[26rpx] font-medium text-gray-800">¥{{ goodsStore.totalFee }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="w-360px m-y-2 flex-center justify-around">
          <view class="w-40px h-40px flex-col-center">
            <view class="i-local-share-bold w-24px h-24px" />
            <view class="text-xs">分享</view>
          </view>
          <view class="w-40px h-40px flex-col-center" @click="toHelp">
            <view class="i-local-customer w-24px h-24px" />
            <view class="text-xs">客服</view>
          </view>
          <nut-button 
            :disabled="!agree || payLoading" 
            :loading="payLoading"
            class="important:w-150px font-bold text-lg"
            :type="(agree && !payLoading) ? 'primary' : 'default'" 
            @click="actionPay"
          >
            {{ payLoading ? '处理中...' : '立即购买' }}
          </nut-button>
        </view>
      </view>

      <nut-sku v-model:visible="visible" :sku="data?.sku" :goods="data?.goods" @selectSku="selectSku"
        @clickBtnOperate="toPay">
        <template #sku-stepper class="w-360px">
          <view class="w-360px flex justify-between items-center">
            <view class="text-13px text-black font-bold">购买数量:</view>
            <nut-input-number v-model="num" class="m-r-20" :button-size="30" :input-width="50" />
          </view>
        </template>
      </nut-sku>
    </view>
  </basic-layout>
</template>

<style lang="scss">
.rchs{
  img{
    width: 100% !important;
    height: auto !important;
  }
}
.swiper_item {
  height: 200px;
}

.swiper_img {
  height: 100%;
  width: 100%;
  border-radius: 24rpx;
  object-fit: cover;
}

.swiper-pagination {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 46px;
  height: 22px;
  background: rgba(0, 0, 0, 0.33);
  border-radius: 22px;
  text-align: center;
  color: #fff;
  font-size: 14px;
}
</style>
